package com.educate.common.utils.converter;

import org.springframework.beans.BeanUtils;
import org.springframework.core.convert.converter.Converter;

public class CopyNonEmptyPropConverter<S, T> implements Converter<S, T> {

    private final Class<T> resultTypeClass;

    public CopyNonEmptyPropConverter(Class<T> resultTypeClass) {
        this.resultTypeClass = resultTypeClass;
    }

    @Override
    public T convert(S source) {
        if (source == null) {
            return null;
        }
        if (resultTypeClass.isAssignableFrom(source.getClass())) {
            return (T) source;
        }
        T result = org.springframework.beans.BeanUtils.instantiate(resultTypeClass);
        BeanUtils.copyProperties(source, result);
        return result;
    }
}
